from time import gmtime, strftime
import time, datetime

from Strategy.config import STATIC
from MarketData.const import CONST
from Server.Web.send import send_web_thread


class PATH:
    ROOTFOLDER = '/Volumes/Work/Nanshuang/pairs_trading_new'


def output(file_name, element):
    currentTime = strftime("%Y-%m-%d %H:%M:%S", gmtime())

    book = open(file_name,'a+')
    book.write(currentTime + "  " + element + '\r\n')
    book.close()


def output_Response(array):
    Ltime = datetime.datetime.now().timestamp()
    
    # output to database
    array_send = []
    for element in array:
        response = dict()
        response['logtime'] = Ltime
        response['response'] = str(element)
        array_send.append(response)

    send_web_thread('order_response', array_send)


def output_Array(file_name, array):
    UTCTime = gmtime()
    Ltime = datetime.datetime.now().timestamp()
    currentTime = strftime("%Y-%m-%d %H:%M:%S", UTCTime)

    #output to text
    book = open(file_name,'a+')
    for element in array:
        book.write(currentTime + "  " + element + '\r\n')
    book.close()


def output_MarketData(pairquote):
    Ltime = datetime.datetime.now().timestamp()
    # output to database
    market_send = []
    for key, item in pairquote.items():
        quote = dict()
        quote['logtime'] = Ltime
        quote['platform'] = str(key)
        quote['price_bid'] = item.price_bid
        quote['price_ask'] = item.price_ask
        quote['volume_bid'] = item.volume_bid
        quote['volume_ask'] = item.volume_ask
        market_send.append(quote)
    send_web_thread('market_data', market_send)


def output_newOrder(order_new):
    Ltime = datetime.datetime.now().timestamp()

    # output to database
    trade_send = []
    for element in order_new:
        order = dict()
        order['logtime'] = Ltime
        order['platform'] = element['platform']
        order['commodity_cur'] = element['commodity_cur']
        order['base_cur'] = element['base_cur']
        order['type'] = element['type']
        order['order'] = element['order']
        order['quantity'] = element['quantity']
        order['price'] = element['price']
        trade_send.append(order)

    send_web_thread('trade', trade_send)


def output_Balance(currency, account, flag):
    UTCTime = gmtime()
    Ltime = datetime.datetime.now().timestamp()
    currentTime = strftime("%Y-%m-%d %H:%M:%S", UTCTime)

    for cur in currency:
        if cur != 'CNY' and cur != 'USD' and (cur, 'BTC') not in STATIC.price:
            return
        elif cur == 'USD' or cur == 'CNY':
            if ('USDT', 'BTC') not in STATIC.price:
                return
    
    STATIC.price['USD', 'BTC'] = STATIC.price['USDT', 'BTC']
    STATIC.price['CNY', 'BTC'] = STATIC.price['CNY', 'USD'] * STATIC.price['USD', 'BTC']
    
    # 1 summary
    # 1.1 summary of quantity
    balance_sum = dict()
    balance_sum['logtime'] = Ltime
    balance_sum['platform'] = 'summary'
    balance_sum['Total(BTC)'] = 0

    for cur in currency:
        balance_sum[cur] = 0

    for type in account:
        for platf in account[type]:
            for cur in currency:
                if cur in account[type][platf].balance:
                    balance_sum[cur] += account[type][platf].balance[cur]

    for key, item in STATIC.account_cash.items():
        balance_sum[key] += item

    for cur in currency:
        balance_sum['Total(BTC)'] += balance_sum[cur] * STATIC.price[cur, 'BTC']
    balance_sum['Total(USD)'] = balance_sum['Total(BTC)'] * STATIC.price['BTC', 'USDT'] * STATIC.price['USDT', 'USD']

    balance_sum['Value(BTC)'] = balance_sum['Total(BTC)'] / STATIC.quantity_BTC
    balance_sum['Value(USD)'] = balance_sum['Total(USD)'] / STATIC.quantity_USD

    # 1.2 summary of quantity percentage
    balance_pert = dict()
    balance_pert['logtime'] = Ltime
    balance_pert['platform'] = 'percentage'
    for cur in currency:
        balance_pert[cur] = balance_sum[cur] * STATIC.price[cur, 'BTC'] / balance_sum['Total(BTC)']

    # 1.3 summary of price on BTC
    balance_price = dict()
    balance_price['logtime'] = Ltime
    balance_price['platform'] = 'price(BTC)'
    for cur in currency:
        balance_price[cur] = STATIC.price[cur, 'BTC']

    # 1.4 send to database
    balance_send = []
    balance_send.append(balance_sum)
    balance_send.append(balance_pert)
    balance_send.append(balance_price)

    if len(STATIC.PlatformList_valid) == len(CONST.PlatformList):
        if flag == 'real':
            send_web_thread('update_balance', balance_send)
        else:
            send_web_thread('update_balance_estimate', balance_send)

    """
    #2 output to text
    book = open(file_name,'a+')

    #2.1 account balance
    for type in account:
        for platf in account[type]:
            output_str = '%-20s' %(type)
            output_str += '%-20s' %(platf)
            for cur in currency:
                if cur in account[type][platf].balance:
                    output_str += '%-20.8f' %(account[type][platf].balance[cur])
                else:
                    output_str += '%-20s' %(0)
            book.write(currentTime + "  " + output_str + '\r\n')

    #2.2 summary
    output_str = '%-20s' %("summary")
    output_str += '%-20s' %("")
    for cur in currency:
        output_str += '%-20.8f' %(balance_sum[cur])

    output_str += '%-20.8f' %(balance_sum['Total(BTC)'])
    output_str += '%-20.8f' %(balance_sum['Total(USD)'])
    output_str += '%-20.8f' %(balance_sum['Value(BTC)'])
    output_str += '%-20.8f' %(balance_sum['Value(USD)'])

    book.write(currentTime + "  " + output_str + '\r\n')

    #2.3 price
    output_str = '%-20s' % balance_price['platform']
    output_str += '%-20s' %("")
    for cur in currency:
        output_str += '%-20.8f' % balance_price[cur]

    book.write(currentTime + "  " + output_str + '\r\n')

    book.close()
    """